package cn.mabach.goods.service.impl;


import cn.mabach.cms.entity.PrefrenceAreaProductRelationEntity;
import cn.mabach.cms.entity.SubjectProductRelationEntity;

import cn.mabach.exception.RRException;
import cn.mabach.goods.feign.PrefrenceAreaProductRelationServiceFeign;
import cn.mabach.goods.feign.SubjectProductRelationServiceFeign;

import cn.mabach.goods.dao.*;
import cn.mabach.goods.dto.ProductParam;
import cn.mabach.goods.dto.ProductResult;
import cn.mabach.goods.entity.ProductEntity;
import cn.mabach.goods.entity.SkuStockEntity;
import cn.mabach.goods.service.ProductService;
import cn.mabach.goods.vo.ProductQueryParam;

import cn.mabach.result.PageResult;
import cn.mabach.result.RS;
import cn.mabach.utils.BeanUtilsMabach;
import cn.mabach.utils.SnowflakeIdWorker;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@Slf4j
public class ProductServiceImpl extends ServiceImpl<ProductDao, ProductEntity> implements ProductService {

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private SkuStockDao skuStockDao;
    @Autowired
    private ProductLadderDao productLadderDao;

    @Autowired
    private ProductFullReductionDao productFullReductionDao;

    @Autowired
    private MemberPriceDao memberPriceDao;
    @Autowired
    private ProductAttributeValueDao productAttributeValueDao;
    @Autowired
    private SubjectProductRelationServiceFeign subjectProductRelationServiceFeign;
    @Autowired
    private PrefrenceAreaProductRelationServiceFeign prefrenceAreaProductRelationServiceFeign;

    /**
     * 创建商品
     */
    @Override
    @Transactional
//    @LcnTransaction
    public RS saveE(@RequestBody ProductParam entity) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Boolean flag=false;

        //创建商品
        ProductEntity productEntity = BeanUtilsMabach.doToDto(entity, ProductEntity.class);
        long id = snowflakeIdWorker.nextId();
        productEntity.setId(id);
        this.save(productEntity);

        //关联阶梯价格
        setRelation(entity.getProductLadderList(),productLadderDao,id);
        //关联满减价格
        setRelation(entity.getProductFullReductionList(),productFullReductionDao,id);
        //关联会员价格
        setRelation(entity.getMemberPriceList(),memberPriceDao,id);
        //处理sku的SN编码
        List<SkuStockEntity> skuStockEntities = setSkuSN(entity.getSkuStockList(), id);
        //关联sku库存信息
        setRelation(skuStockEntities,skuStockDao,id);
        //关联商品参数,添加自定义商品规格
        setRelation(entity.getProductAttributeValueList(),productAttributeValueDao,id);
        //关联专题
        List<SubjectProductRelationEntity> subjectProductRelationList = entity.getSubjectProductRelationList();
        for (SubjectProductRelationEntity subjectProductRelationEntity : subjectProductRelationList) {

            subjectProductRelationEntity.setProductId(id);
            subjectProductRelationServiceFeign.saveE(subjectProductRelationEntity);
        }
        //关联优选
        List<PrefrenceAreaProductRelationEntity> prefrenceAreaProductRelationList = entity.getPrefrenceAreaProductRelationList();
        for (PrefrenceAreaProductRelationEntity prefrenceAreaProductRelationEntity : prefrenceAreaProductRelationList) {
            prefrenceAreaProductRelationEntity.setProductId(id);
            prefrenceAreaProductRelationServiceFeign.saveE(prefrenceAreaProductRelationEntity);
        }


        flag=true;
        if (flag){
            return RS.ok();
        }

        return RS.error();
    }


    /**
     * 更改商品
     */
    @Override
    public RS updateByIdE(ProductParam entity) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Boolean flag=false;

        Long id = entity.getId();

//        更改商品本类信息
        ProductEntity productEntity=entity;
        this.updateById(productEntity);

        //修改sku库存信息
        updateRelation(entity.getSkuStockList(),skuStockDao,id);
        //修改阶梯价格
        updateRelation(entity.getProductLadderList(),productLadderDao,id);
        //修改满减价格
        updateRelation(entity.getProductFullReductionList(),productFullReductionDao,id);
        //修改会员价格
        updateRelation(entity.getMemberPriceList(),memberPriceDao,id);
        //修改商品参数,添加自定义商品规格
        updateRelation(entity.getProductAttributeValueList(),productAttributeValueDao,id);
        //修改关联专题
        List<SubjectProductRelationEntity> relationList = entity.getSubjectProductRelationList();
        for (SubjectProductRelationEntity subjectProductRelationEntity : relationList) {
            subjectProductRelationEntity.setProductId(id);
            subjectProductRelationServiceFeign.saveE(subjectProductRelationEntity);
        }
        //修改关联优选
        List<PrefrenceAreaProductRelationEntity> prefrenceAreaProductRelationList = entity.getPrefrenceAreaProductRelationList();
        for (PrefrenceAreaProductRelationEntity prefrenceAreaProductRelationEntity : prefrenceAreaProductRelationList) {
            prefrenceAreaProductRelationEntity.setProductId(id);
            prefrenceAreaProductRelationServiceFeign.saveE(prefrenceAreaProductRelationEntity);
        }

        flag=true;
        if (flag){
            return RS.ok();
        }
        return RS.error();
    }


    /**
     * 分页查询
     */
    @Override
    public RS<PageResult<ProductEntity>> queryPage(@RequestBody ProductQueryParam productQueryParam,
                                                   @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                   @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        if (pageSize>20){
            return RS.error("ProductServiceImpl非法参数");
        }
        IPage<ProductEntity> page = this.page(
                new Page<ProductEntity>(pageNum,pageSize),
                new QueryWrapper<ProductEntity>().eq("delete_status",0)
                        .like(!StringUtils.isEmpty(productQueryParam.getKeyword()),"name",productQueryParam.getKeyword())
                .eq(!StringUtils.isEmpty(productQueryParam.getProductSn()),"product_sn",productQueryParam.getProductSn())
                .eq(productQueryParam.getBrandId()!=null,"brand_id",productQueryParam.getBrandId())
                .eq(productQueryParam.getProductCategoryId()!=null,"product_category_id",productQueryParam.getProductCategoryId())
                .eq(productQueryParam.getPublishStatus()!=null,"publish_status",productQueryParam.getPublishStatus())
                .eq(productQueryParam.getVerifyStatus()!=null,"verify_status",productQueryParam.getVerifyStatus())

        );

        log.info("ProductServiceImpl:{}",Thread.currentThread().getName());
        return RS.ok(new PageResult(page));
    }

    /**
     * 根据ID查询
     */
    @Override
    public RS<ProductResult> getByIdE(@RequestParam("id") Long id) {
        ProductResult byIdE = productDao.getByIdE(id);

        return RS.ok(byIdE);
    }

    @Override
    public RS<ProductEntity> getOneById(@RequestParam("id") Long id) {
        ProductEntity productEntity = this.getById(id);
        return RS.ok(productEntity);
    }


    //根据商品名称或货号模糊查询
//    @RequestMapping(value = "/simpleList", method = RequestMethod.GET)
//    @ResponseBody
//    public RS<List<ProductEntity>> getList(String keyword) {
//
//        return RS.ok();
//    }

    /**
     * 审核商品
     */

    public RS updateVerifyStatus(@RequestParam("id") Long id,
                                 @RequestParam("verifyStatus") Integer verifyStatus) {

        ProductEntity productEntity = new ProductEntity();
        productEntity.setId(id);
        productEntity.setVerifyStatus(verifyStatus);
        this.updateById(productEntity);
        return null;
    }

    /**
     * 批量推荐商品
     */
    @Transactional
    public RS updateRecommendStatus(@RequestParam("ids") List<Long> ids,
                                    @RequestParam("recommendStatus") Integer recommendStatus) {
        for (Long id : ids) {

            ProductEntity productEntity = new ProductEntity();
            productEntity.setId(id);
            productEntity.setRecommandStatus(recommendStatus);
            boolean b = this.updateById(productEntity);
            if (!b){
                return RS.error();
            }
        }

        return RS.ok();
    }

    /**
     * 批量上下架商品
     */
    @Transactional
    public RS updatePublishStatus(@RequestParam("ids") List<Long> ids,
                                  @RequestParam("publishStatus") Integer publishStatus) {
        for (Long id : ids) {
            ProductEntity productEntity = new ProductEntity();
            productEntity.setId(id);
            productEntity.setPublishStatus(publishStatus);
            boolean b = this.updateById(productEntity);
            if (!b){
                return RS.error();
            }
        }
        return RS.ok();

    }

    /**
     * 批量设为新品
     */

    @Transactional
    public RS updateNewStatus(@RequestParam("ids") List<Long> ids,
                              @RequestParam("newStatus") Integer newStatus) {
        for (Long id : ids) {

            ProductEntity productEntity = new ProductEntity();
            productEntity.setId(id);
            productEntity.setNewStatus(newStatus);
            boolean b = this.updateById(productEntity);
            if (!b){
                return RS.error();
            }

        }
        return RS.ok();

    }

    /**
     * 批量逻辑删除或恢复
     */

    @Transactional
    public RS updateDeleteStatus(@RequestParam("ids") List<Long> ids,
                                 @RequestParam("deleteStatus") Integer deleteStatus) {

        for (Long id : ids) {
            ProductEntity productEntity = new ProductEntity();
            productEntity.setId(id);
            productEntity.setDeleteStatus(deleteStatus);
            boolean b = this.updateById(productEntity);
            if (!b){
                return RS.error();
            }
        }
        return RS.ok();
    }




    /**
     * 批量关联
     */

    @Transactional
    public void setRelation(List entityList,Object dao,Long productId) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        if (!CollectionUtils.isEmpty(entityList)){

            for (Object o : entityList) {

                try {
                    Method setProductId = o.getClass().getMethod("setProductId", Long.class);
                    setProductId.invoke(o,productId);

                    Method insert = dao.getClass().getMethod("insert", o.getClass());
                    insert.invoke(dao, o);
                } catch (Exception e) {
                    log.error("商品关联"+o.getClass().getName()+"出错：{}",e.getMessage());
                    throw new RRException("商品关联"+o.getClass().getName()+"出错:"+e.getMessage(),e);
                }

            }
        }

    }

    /**
     * 批量修改关联
     */
    @Transactional
    public void updateRelation(List entityList,Object dao,Long productId) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        if (!CollectionUtils.isEmpty(entityList)){

            for (Object o : entityList) {

                try {
                    Method setProductId = o.getClass().getMethod("setProductId", Long.class);
                    setProductId.invoke(o,productId);

                    Method insert = dao.getClass().getMethod("updateById", o.getClass());
                    insert.invoke(dao, o);
                } catch (Exception e) {
                    log.error("更改商品关联"+o.getClass().getName()+"出错：{}",e.getMessage());
                    throw new RRException("更改商品关联"+o.getClass().getName()+"出错:"+e.getMessage(),e);
                }

            }
        }

    }

    public List<SkuStockEntity> setSkuSN(List<SkuStockEntity> skuSN,Long productId){
        if (CollectionUtils.isEmpty(skuSN)){
            return null;
        }

        for (int i = 0; i < skuSN.size(); i++) {
            SkuStockEntity skuStockEntity = skuSN.get(i);

            if (StringUtils.isEmpty(skuStockEntity.getSkuCode())){
                StringBuffer sb = new StringBuffer();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
                String format = simpleDateFormat.format(new Date());
                sb.append(format).append(String.format("%019d",productId))
                        .append(String.format("%03d",i+1));

                skuStockEntity.setSkuCode(sb.toString());
            }
        }
        return skuSN;
    }







}